<script setup>
// 路由
const router = useRouter()
// 用户store
const userStore = useUserStore()

// 表单数据
const username = ref('')
const password = ref('')

// 使用登录API
const { runAsync: login, loading } = loginApi()

// 登录方法
const handleLogin = async () => {
  try {
    // 加密密码
    const encryptedPassword = md5EncryptWithSalt(password.value)

    // 调用登录API
    const res = await login({
      username: username.value,
      password: encryptedPassword
    })

    // 登录成功，保存用户信息和token
    userStore.loginSuccess({
      token: res.data.token,
      userInfo: res.data.userInfo
    })

    showToast('登录成功')

    // 登录成功后跳转到首页
    router.replace('/')
  } catch (error) {
    console.error('登录失败:', error)
    showToast(error?.message || '登录失败，请重试')
  }
}

// 跳转到注册页面
const goToRegister = () => {
  router.push('/register')
}
</script>

<template>
  <div class="min-h-screen bg-gray-100 flex flex-col">
    <div class="mt-auto pb-safe bg-white rounded-t-[32px] pt-10 pb-10 px-6 min-h-[60vh] shadow-lg">
      <h2 class="text-center text-2xl font-bold mb-10 text-gray-900">登录</h2>
      <van-form @submit="handleLogin">
        <van-cell-group inset>
          <van-field
            v-model="username"
            name="username"
            label="用户名"
            placeholder="请输入用户名"
            :rules="[{ required: true, message: '请填写用户名' }]"
          />
          <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入密码"
            :rules="[{ required: true, message: '请填写密码' }]"
          />
        </van-cell-group>
        <div class="mt-10">
          <BaseButton
            round
            block
            type="primary"
            native-type="submit"
            :loading="loading"
            class="w-full"
          >
            登录
          </BaseButton>
          <div class="mt-8 text-center text-sm text-gray-500">
            <span>还没有账号？</span>
            <span class="text-blue-500 ml-1 cursor-pointer font-medium" @click="goToRegister"
              >立即注册</span
            >
          </div>
        </div>
      </van-form>
    </div>
  </div>
</template>
<route>
  { 
    path: '/login',
    name: 'login',
    meta: {
      title: '登录',
      hideTabbar: true,
    }
  }
</route>
